package com.chinawlx.wlxteacher.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.chinawlx.wheelview.OptionsPickerView;
import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXGetCodeBean;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.widget.radiogroup.WLXFlowRadioGroup;
import com.chinawlx.wlxteacher.wlx_schedule;
import com.chinawlx.wlxteacher.wlx_scheduleDao;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**
 * 班级请假界面
 * <p/>
 * Created by yyc on 2016/8/3.
 */
public class ClazzLeaveActivity extends WLXBaseActivity {
    @BindView(R.id.tv_leave_date)
    TextView leaveDate;
    @BindView(R.id.tv_clazz)
    TextView tvClazz;
    @BindView(R.id.rg_leave)
    WLXFlowRadioGroup leaveRadioGroup;

    private RadioButton[] radioButtons;
    private String[] titles = {"学习考试", "身体不适", "家中急事", "假日休息", "婚假产假"};
    private String[] reason_codes = {"study", "health", "housework", "holiday", "marriage"};
    private String reasonCode;
    private String schedule_id;//课程ID
    private OptionsPickerView pvOptions;
    private List<wlx_schedule> mWlx_schedules;
    private ArrayList<String> options1Items = new ArrayList<>();
    private boolean NO_DATA = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clazzleave);
        ButterKnife.bind(this);
        init();
    }

    public void init() {
        initData();
        initView();
    }

    private void initData() {
        initRadioButton();
        loadDataFromDb();
    }


    //从数据库拿数据
    private void loadDataFromDb() {
        //拿到课程数据,比当前时间大的才显示
        mWlx_schedules = WLXGreenDaoUtil.getScheduleDao().queryBuilder().where
                (wlx_scheduleDao.Properties.Grade_id
                                .eq(WLXConstant.GRADE_ID), wlx_scheduleDao.Properties
                                .Teacher_user_id.eq
                                        (WLXConstant.USER_ID)
                        , wlx_scheduleDao.Properties.Opening_date.gt(System.currentTimeMillis() /
                                1000)
                ).orderAsc(wlx_scheduleDao.Properties
                .Opening_date)
                .list();

        options1Items.clear();
        for (wlx_schedule bean : mWlx_schedules) {
            //开始时间,结束时间
            String startTime = WLXDateUtil.getDateToString(bean.getOpening_date(), "MM月dd日 HH:mm");
            String endTime = WLXDateUtil.getDateToString(bean.getClosing_date(), "HH:mm");
            options1Items.add(startTime + "-" + endTime);
        }
    }

    private void initView() {
        tvClazz.setText(WLXConstant.GRADE_TITLE);
        initWheelView();
        leaveRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int i = 0; i < radioButtons.length; i++) {
                    if (radioButtons[i].getId() == checkedId) {
                        reasonCode = reason_codes[i];
                        //得到选中的文字
                    }
                }
            }
        });
    }

    private void initWheelView() {
        pvOptions = new OptionsPickerView(this);
        pvOptions.setPicker(options1Items);
        pvOptions.setTitle("选择课次");
        //设置是否循环滚动
        pvOptions.setCyclic(false);
        //设置选中的item位置
        pvOptions.setSelectOptions(2);
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                //返回选中的item位置
                wlx_schedule wlx_schedule = mWlx_schedules.get(options1);
                schedule_id = wlx_schedule.getSchedule_id();

                String index = options1Items.get(options1);
                leaveDate.setText("请假时间 " + index);
                leaveDate.setVisibility(View.VISIBLE);
            }
        });
        NO_DATA = options1Items.size() == 0;
    }

    @OnClick({R.id.iv_back_clazz_leave, R.id.rl_time_select, R.id.tv_save})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back_clazz_leave:      //返回
                finish();
                break;
            case R.id.rl_time_select:           //时间选择
                if (NO_DATA) {
                    WLXCustomToast.show("没有课次");
                    return;
                }
                pvOptions.show();
                break;
            case R.id.tv_save:           //保存数据,网络请求
                if (checkIfComplete()) {
                    requestNet2Leave();
                } else {
                    Toast.makeText(ClazzLeaveActivity.this, "未完成选择", Toast.LENGTH_SHORT)
                            .show();
                }
                break;

        }
    }

    private void requestNet2Leave() {
        WLXHttpRxHelper.getInstance().teacherLeave(WLXConstant.GRADE_ID, schedule_id, reasonCode,
                new Subscriber<WLXGetCodeBean>() {


                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(WLXGetCodeBean wlxGetCodeBean) {
                        if (wlxGetCodeBean.getCode() == 0) {
                            new AlertView("提示", "请假成功", null, new String[]{"确定"}, null,
                                    ClazzLeaveActivity.this,
                                    AlertView.Style.Alert, new OnItemClickListener() {
                                @Override
                                public void onItemClick(Object o, int position) {
                                    ClazzLeaveActivity.this.finish();
                                }
                            }).show();
                        } else {
                            Toast.makeText(ClazzLeaveActivity.this, wlxGetCodeBean.getMsg(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    //检查是否全部都选择了,并且请求数据已经OK
    private boolean checkIfComplete() {
        if (TextUtils.isEmpty(reasonCode)) {
            Toast.makeText(ClazzLeaveActivity.this, "请选择请假原因", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(schedule_id)) {
            Toast.makeText(ClazzLeaveActivity.this, "请选择请假时间", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 动态添加内容
     */
    private void initRadioButton() {
        WindowManager manager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
        int width = manager.getDefaultDisplay().getWidth();
        // 动态加载radiobutton的时候要用  radioGroup.layoutParams 来实现
        RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(width / 3 - 65,
                WRAP_CONTENT);
        layoutParams.setMargins(18, 13, 18, 10);
        radioButtons = new RadioButton[titles.length];
        for (int i = 0; i < radioButtons.length; i++) {
            radioButtons[i] = new RadioButton(this);
            radioButtons[i].setText(titles[i]);
            radioButtons[i].setButtonDrawable(null);
            radioButtons[i].setBackgroundResource(R.drawable.selector_feedback);
            radioButtons[i].setTextColor(this.getResources().getColorStateList(R.color
                    .color_feedback_name));
            radioButtons[i].setGravity(Gravity.CENTER);
            radioButtons[i].setTag(i);
            radioButtons[i].setId(i);
            radioButtons[i].setLayoutParams(layoutParams);
            leaveRadioGroup.addView(radioButtons[i]);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (pvOptions.isShowing()) {
                pvOptions.dismiss();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
